package com.herui.sdyu_lib.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by amanda.shan on 2016/7/13.
 */
public abstract class ViewHolderAdapter<VH extends ViewHolderAdapter.ViewHolder, T> extends BaseAdapter {

    protected List<T> list;
    protected Context context;
    private LayoutInflater mInflater;

    public ViewHolderAdapter(Context context) {
        this.init(context, new ArrayList());
    }

    public ViewHolderAdapter(Context context, List<T> list) {
        this.init(context, list);
    }

    private void init(Context context, List<T> list) {
        this.list = list;
        this.context = context;
        mInflater = LayoutInflater.from(context);
    }

    public List<T> getList() {
        return this.list;
    }

    public void setList(List<T> list) {
        this.list = list;
    }

    public void clear() {
        this.list.clear();
        this.notifyDataSetChanged();
    }

    public void addAll(List<T> list) {
        if (list != null) {
            this.list.addAll(list);
            this.notifyDataSetChanged();
        }

    }

    public int getCount() {
        return this.list == null ? 0 : this.list.size();
    }

    public T getItem(int position) {
        return this.list.get(position);
    }

    public long getItemId(int position) {
        return (long) position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {

        VH holder;
        if (convertView == null) {
            holder = onCreateViewHolder(parent, position);
            holder.view.setTag(holder);
            convertView = holder.view;
        } else {
            holder = (VH) convertView.getTag();
        }

        onBindViewHolder(convertView, holder, position);
        return holder.view;
    }

    public abstract VH onCreateViewHolder(ViewGroup parent, int position);

    public abstract void onBindViewHolder(View parent, VH holder, int position);

    public View inflate(int layoutResID, ViewGroup parent) {
        View view = mInflater.inflate(layoutResID, parent, false);
        return view;
    }

    public void refreshData() {
        this.notifyDataSetChanged();
    }

    public void refreshData(List<T> list) {
        this.list = list;
        this.notifyDataSetChanged();
    }

    public static class ViewHolder {
        View view;

        public ViewHolder(View view) {
            this.view = view;
        }
    }
}
